package com.archie.zhufengfm;

import android.app.Activity;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.archie.zhufengfm.adapters.AlbumTracksAdapter;
import com.archie.zhufengfm.entity.AlbumDetails;
import com.archie.zhufengfm.entity.Track;
import com.archie.zhufengfm.service.MusicPlayService;
import com.archie.zhufengfm.tasks.AlbumsTask;
import com.archie.zhufengfm.tasks.TaskCallback;
import com.archie.zhufengfm.tasks.TaskResult;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class AlbumDetailActivity extends Activity implements TaskCallback, AdapterView.OnItemClickListener {

    private long albumId, trackId;

    private int pager = 1;
    private ArrayList<Track> tracks;
    private AlbumTracksAdapter adapter;
    private AlbumsTask albumsTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album_detail);

        ListView list = (ListView) findViewById(R.id.album_listView);

        albumId = getIntent().getLongExtra("albumId", -1);

        trackId = getIntent().getLongExtra("trackId",-1);

        if(albumId != -1 && trackId != -1) {

            albumsTask = new AlbumsTask(this, albumId, trackId, pager);
            albumsTask.execute();

        }

        tracks = new ArrayList<>();

        adapter = new AlbumTracksAdapter(this, tracks);

        list.setAdapter(adapter);

        list.setOnItemClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // activity 销毁的时候取消异步任务
        albumsTask.cancel(true);
    }

    @Override
    public void onTaskFinished(TaskResult result) {

        if (result != null) {

            List<Track> data = ((AlbumDetails) result.data).getTracks();

            tracks.addAll(data);

            adapter.notifyDataSetChanged();

        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // 跳到播放界面
        Intent intent = new Intent(this, PlayActivity.class);

        intent.putParcelableArrayListExtra("tracks", tracks);

        intent.putExtra("tracks_index", position);

        startActivity(intent);

    }
}
